//
//  ST_DTInputBar.swift
//  DrinkTogether
//
//  Created by DouLei on 2018/6/28.
//  Copyright © 2018 DouLei. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyUserDefaults
import SwifterSwift
import SwiftyJSON
import MobileCoreServices
import AVFoundation
import Photos
import ISEmojiView
import TZImagePickerController


enum ST_DTInputBarHeightStatus {
    //    普通状态，弹出键盘 ，表情 ，选择图片
    case normal,keybroad,face,selectPicture,speaker
}


//MARK:- 上传类型
enum UploadType :Int {
    case unknow = 0
    case video = 2
    case image = 1
}
 


class ST_DTInputBar: UIView {
    
    static let input_bar_height = 49.cgFloat
    
    static let select_media_root_view_height:CGFloat = 80 + BTSafeAreaBottom
    
    static var is_shared_emoji = true
    
    var uploadType : UploadType = .unknow
    private lazy var picture_images = [UIImage]()
    private  var last_select_assets  = [PHAsset]()
    
    
    weak var vc:ST_PrivateChatViewController?
    
    //视频云地址
    var network_video_url = ""

    
    //    MARK: - Properties
//    lazy var back_image_view:UIImageView = {
//        let control = UIImageView()
//        control.image = ST_ImageUtils.imageName("陌生人_bj_输入框")
//        return control
//    }()
    
    lazy var send_image_btn:UIButton = {
        let control = UIButton.init(type: .custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("陌生人_icon_发送照片")!)
        control.addTarget(self, action: #selector(show_operation_view), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    lazy var center_btn:UIButton = {
        let control = UIButton.init(type: .custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_表情")!)
        control.addTarget(self, action: #selector(show_emoji_view), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    lazy var voice_btn:UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_语音输入")!)
        
        btn.setImage(ST_ImageUtils.imageName("mycenter_icon_键盘")!, for: UIControl.State.selected)
        
        btn.addTarget(self, action: #selector(audio_record_hanlde(sender:)), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    lazy var input_status_control_btn:UIButton = {
        
        let btn = UIButton.init(type: .custom)
        
        btn.setImageForAllStates(ST_ImageUtils.imageName("消息_inputBar_输入_normal")!)
        
        btn.setImage(ST_ImageUtils.imageName("消息_inputBar_输入_selected")!, for: UIControl.State.selected)
        
        btn.addTarget(self, action: #selector(show_emoji_view), for: UIControl.Event.touchUpInside)
        
        return btn
    }()
    
    let input_text_color = Color.init(hex: 0x00527F)!
    
    let input_placeholder_text_color = Color.init(hex: 0x999999)!
    
    var input_placeholder_text = ""{
        didSet{
            if inputTextView.text.isEmpty {
                inputTextView.text = input_placeholder_text
                inputTextView.textColor = input_placeholder_text_color
            }
        }
    }
    
    lazy var inputTextView:UITextView = {
        let control = UITextView.init(frame: CGRect.zero)
        control.backgroundColor = Color.init(hexString: "#F2F4F7")
        control.cornerRadius = 6
        control.tintColor = Color.init(hex:  0xcccccc)!
        control.textColor = input_placeholder_text_color
        control.font = DTChatTextFont
        control.returnKeyType = .send
        control.enablesReturnKeyAutomatically  = true
        control.inputAccessoryView = UIView()
        control.delegate = self
        control.showsVerticalScrollIndicator = false
       return control
    }()
    
    fileprivate lazy var emojiView:EmojiView = {
        
        let keyboardSettings = KeyboardSettings(bottomType: BottomType.categories)
        keyboardSettings.countOfRecentsEmojis = 12
        keyboardSettings.updateRecentEmojiImmediately = true
        let emojiView = EmojiView(keyboardSettings: keyboardSettings)
        emojiView.translatesAutoresizingMaskIntoConstraints = false
        emojiView.delegate = self
        return emojiView
    }()
    
    
    
    
    lazy var speaker_btn:ST_ChatToolBarAudioButton = {
       let control = ST_ChatToolBarAudioButton()
        control.backgroundColor = Color.init(hexString: "#F2F4F7")!
        control.cornerRadius = 20
        return control
    }()
    
    
    /*
    lazy var emojiView:MPTabEmojiView = {
        
        var control = MPTabEmojiView()
    
        control.backgroundColor = Color.white
        control.isHidden = true
        
        control.start_lauch_block = { (rect,model) in
            self.start_lauch_block?(rect,model)
        }
        
        control.stop_lauch_block = {
            self.stop_lauch_block?()
        }
        
        control.didSelected = { frame,model in
            self.didSelected?(frame,model)
        }
        
        return control
    }()
    */
    
    lazy var select_media_root_view:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        control.isHidden = true
        return control
    }()
    
    lazy var switch_picture:UIButton = {
        
        let control = UIButton.init(type: .custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("n_私信_icon_发送图片")!)
        control.addTarget(self, action: #selector(select_picture_handle), for: UIControl.Event.touchUpInside)
//        control.isHidden = true
        return control
    }()
    
    lazy var switch_picture_label:UILabel = {
        
        let control = UILabel()
        control.font = UIFont.systemFont(ofSize: 12)
        control.text = "照片"
        control.textColor = UIColor.init(hex: 0x999999)
        control.textAlignment = .center
//        control.isHidden = true
        return control
    }()
    
    
    
    lazy var take_picture_btn:UIButton = {
        
        let control = UIButton.init(type: .custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("n_私信_icon_录制")!)
        control.addTarget(self, action: #selector(take_picture_handle), for: UIControl.Event.touchUpInside)
//        control.isHidden = true
        return control
    }()
    
    lazy var take_picture_label:UILabel = {
        let control = UILabel()
        control.font = UIFont.systemFont(ofSize: 12)
        control.text = "拍摄"
        control.textColor = UIColor.init(hex: 0x999999)
        control.textAlignment = .center
//        control.isHidden = true
        return control
    }()
    
    
    
    //    MARK: - Closure
    var start_lauch_emoji_closure:((CGRect,ChatEmojiCellModel)->())?
    
    var stop_lauch_emoji_closure:(()->())?
    
    var did_select_emoji_closure:((CGRect,ChatEmojiCellModel)->())?
    
    //    缩略图本地路径  原图本地路径
    var send_image_closure:((String,String,CGSize,Bool)->())?
//
    var send_text_closure:((String)->())?
//     缩略图路径 尺寸 本地路径
    var send_video_closure:((String,CGSize,String)->())?
//    更改高度状态的回调
    var modify_height_status:(()->())?
    
//    录制需要外部UI 参与 提供delegate 而不是 Closure
    weak var recordAudioDelegate:DPChatToolBarAudioDelegate?{
        didSet{
            if let delegate = recordAudioDelegate{
                self.speaker_btn.delegate = delegate
            }
        }
    }
//    MARK: - public
    var heightStatus:ST_DTInputBarHeightStatus = .normal {
        didSet{
            
            
            self.select_media_root_view.isHidden = self.heightStatus != .selectPicture
            
//            self.emojiView.isHidden = heightStatus != .face
            
            self.inputTextView.isHidden = self.heightStatus == .speaker
            
            self.speaker_btn.isHidden = self.heightStatus != .speaker
            
            self.voice_btn.isSelected = self.heightStatus == .speaker
            
//            print("speaker_btn hidden:",self.heightStatus != .speaker)
//
//            print("inputTextView hidden:",self.heightStatus == .speaker)
        }
    }
    
    var keyboard_height:CGFloat = 0.0
    
    var emojiViewHeight:CGFloat = 236
    
    lazy var line:UIView = {
        let control = UIView()
        control.backgroundColor = Color.init(hex: 0xF2F4F7)
        return control
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = Color.white
        
        let top_view = UIView()
        top_view.backgroundColor = Color.white
        self.addSubview(top_view)
        self.addSubview(line)
        
        top_view.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.height.equalTo(ST_DTInputBar.input_bar_height)
        }
        
        line.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.height.equalTo(1)
        }
        
//        top_view.addSubview(back_image_view)
        top_view.addSubview(inputTextView)
        top_view.addSubview(send_image_btn)
//        top_view.addSubview(center_btn)
        top_view.addSubview(voice_btn)
        top_view.addSubview(input_status_control_btn)
        
//        back_image_view.snp.makeConstraints { (make) in
//            make.left.right.bottom.top.equalTo(top_view)
//        }
        
        voice_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(send_image_btn)
        }
        
        inputTextView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(voice_btn.snp.right).offset(10)
            make.right.equalTo(input_status_control_btn.snp.left).offset(-10)
            make.height.equalTo(36)
        }
        
        send_image_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-17)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(32)
        }
        
        input_status_control_btn.snp.makeConstraints { (make) in
            make.right.equalTo(send_image_btn.snp.left).offset(-8)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(32)
        }
        
        
        self.addSubview(speaker_btn)
        speaker_btn.isHidden = true
        speaker_btn.snp.makeConstraints { (make) in
            
            make.left.right.bottom.top.equalTo(inputTextView)
        }
        
        
        self.addSubview(select_media_root_view)
        select_media_root_view.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.top.equalTo(top_view.snp.bottom)
            make.height.equalTo(ST_DTInputBar.select_media_root_view_height)
        }
        
        select_media_root_view.addSubview(switch_picture)
        select_media_root_view.addSubview(take_picture_btn)
        select_media_root_view.addSubview(switch_picture_label)
        select_media_root_view.addSubview(take_picture_label)
        
        let gap:CGFloat = iPhonePlusSeries ? 80 : 70
        
        let switchPictureLeftEdge = (ScreenWidth - 34*2 - gap)/2.0
        
        switch_picture.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(switchPictureLeftEdge)
            make.top.equalToSuperview().offset(10)
            make.width.height.equalTo(34)
        }
        
        switch_picture_label.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.switch_picture)
            make.top.equalTo(self.switch_picture.snp.bottom).offset(5)
        }
        
        
        take_picture_btn.snp.makeConstraints { (make) in
            make.left.equalTo(self.switch_picture.snp.right).offset(gap)
            make.top.equalTo(switch_picture)
            make.width.height.equalTo(34)
        }
        
        take_picture_label.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.take_picture_btn)
            make.top.equalTo(self.take_picture_btn.snp.bottom).offset(8)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: -
    //    MARK: - Event
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
       

        if let vc = self.parentViewController as? ST_PrivateChatViewController{
            vc.dismissMessageToolBar()
        }
    }
    
    func setDraft(text:String)  {
        
        self.inputTextView.text = text
        self.inputTextView.textColor = self.input_text_color
        
    }
    
    @objc func select_picture_handle(){
        
        guard let vc = TZImagePickerController.init(maxImagesCount: 9, delegate: nil) else{ return }
        
        
        vc.isSelectOriginalPhoto = false
        
        vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
            
            
            main_thread_execute {

                guard let imageArray = photos else{
                    return
                }
                
                for img in imageArray{
                 
                    self?.picture_images.append(img)
                    
                    self?.heightStatus = .normal
                                            
                    self?.modify_height_status?()
                                            
                    self?.sendImage(img)
                    
                }
            }
        }
                    
        vc.didFinishPickingVideoHandle = {[weak self] image , assets in
            
            
            guard let ast = assets , let thumbnailImage = image else { return  }
            
            let options: PHVideoRequestOptions = PHVideoRequestOptions()
               options.version = .original
            
           PHImageManager.default().requestAVAsset(forVideo: ast, options: options, resultHandler: { (asset, audioMix, info) in
            
            main_thread_execute {
                
                if let tempAsset = asset as? AVURLAsset{
                    
                    let videoUrl = tempAsset.url
                    
                    let filename = UUID().uuidString+".mp4"
                    
                    guard var videoPath = SC.push_peculiarity_directory else { return }
                    
                    videoPath.appendPathComponent(filename)
                    
                    do {
                        try FileManager.default.copyItem(at: videoUrl, to: videoPath)
                    } catch (let error) {
                        print("Cannot copy item at \(videoUrl) to \(videoPath): \(error)")
                        return
                    }
                    
                    let size = thumbnailImage.size
                    
                    main_thread_execute {
                        
                        if let thumbnailUrl = self?.save_image_to_document(image: thumbnailImage){
                            
                            self?.heightStatus = .normal
                            
                            self?.modify_height_status?()
                            
                            self?.send_video_closure?(thumbnailUrl.path,size,videoPath.path)
                            
                        }
                    }
                }
                
                
                
            }
               
           })
        }
        GlobalPresent(toController: vc, animated: true)
        
        
        self.heightStatus = .normal
        
        self.modify_height_status?()
        
    }
    
    
    private func sendImage(_ originalImage:UIImage,isSnapChat:Bool = false) {
        
        
        var thumbnailImage:UIImage!
        
        if originalImage.size.width > 280*2{
            
            thumbnailImage = originalImage.resize_image(targetWidth: 280*2)
        }else{
            thumbnailImage = originalImage
        }
        
        
        guard let thumbnialUrl = save_image_to_document(image: thumbnailImage),let imageUrl = save_image_to_document(image: originalImage) else {
            
            self.heightStatus = .normal
            
            self.modify_height_status?()
            
            return
        }
     
        self.send_image_closure?(thumbnialUrl.path,imageUrl.path,thumbnailImage.size, isSnapChat)
        
    }
    
    
    func deal_video_stream(with array:[UIImage])  {
        
        if let asset  = self.last_select_assets.first{
            //                        第一甄
            if   let image = array.first {
                
                var thumbnailImage:UIImage!
                
                if image.size.width > 280*2{
                    thumbnailImage = image.resize_image(targetWidth: 280*2)
                }else{
                    thumbnailImage = image
                }
                
                thumbnailImage = thumbnailImage.fix_orientation()
                
                PHCachingImageManager().requestAVAsset(forVideo: asset, options: nil) { [weak self](avAsset, audio, info) in
                    
                    if let tempAsset = avAsset as? AVURLAsset{
                        
                        let videoUrl = tempAsset.url
                        
                        let filename = UUID().uuidString+".mp4"
                        
                        guard var videoPath = SC.push_peculiarity_directory else { return }
                        
                        videoPath.appendPathComponent(filename)
                        
                        do {
                            try FileManager.default.copyItem(at: videoUrl, to: videoPath)
                        } catch (let error) {
                            print("Cannot copy item at \(videoUrl) to \(videoPath): \(error)")
                            return
                        }
                        
                        let size = thumbnailImage.size
                        
                        main_thread_execute {
                            
                            if let thumbnailUrl = self?.save_image_to_document(image: thumbnailImage){
                                
                                self?.heightStatus = .normal
                                
                                self?.modify_height_status?()
                                
                                self?.send_video_closure?(thumbnailUrl.path,size,videoPath.path)
                                
                            }
                            
                            
                        }
                    }
                }
            }
        }
    }
    

    @objc func take_picture_handle(){
        
        let vc = ST_RGCameraController()
        
        vc.completeActionBlock = { url, type in

//            DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(true))
            
            if type == .video {
               
                self.saveMovie(mediaStr: url)
            }//如果是图片
            else if type == .image{
                if let originalImage = UIImage.init(contentsOfFile: url){
                    
                    print("BUG拍图-originalImage.size:",originalImage.size)
                    
                    let thumbnailImage = originalImage.resize_image(targetWidth: 140)
                    
                    //                originalImage.scaled(toWidth: 140)
                    guard let thumbnailUrl = self.save_image_to_document(image: thumbnailImage) else{
                        
                        self.heightStatus = .normal
                        
                        self.modify_height_status?()
                        
                        return
                    }
                    
                    self.heightStatus = .normal
                    
                    self.modify_height_status?()
                    
                    self.send_image_closure?(thumbnailUrl.path,url,thumbnailImage.size, false)
                    
                }else{
                    
//                    DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(false))
                }
            }
            
        }
 
        vc.modalPresentationStyle = .fullScreen
        
        self.parentViewController?.present(vc, animated: true, completion: nil)
     
    }
    
    
    private func save_image_to_document(image:UIImage)->URL?{
        // get the documents directory url
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        // choose a name for your image
        let fileName = UUID().uuidString
        // create the destination file url to save your image
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        // get your UIImage jpeg data representation and check if the destination file url already exists
        if let data = image.jpegData(compressionQuality:  1.0),
            !FileManager.default.fileExists(atPath: fileURL.path) {
            do {
                // writes the image data to disk
                try data.write(to: fileURL)
//                print("FILE--URL-2:",fileURL)
                return fileURL
            } catch {
                
                print("saveImageToDocument -- error saving file: \(error)")
                
                return nil
            }
        }
        
        return nil
    }
    
    //开启摄像头
//  func btnRecord() {
//
//    self.heightStatus = .normal
//
//    self.modify_height_status?()
//
//        //第一步，检测摄像头是否可用
//        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
//
//            //根据指定的SourceType来获取该SourceType下可以用的媒体类型，返回的是一个数组
//            if  let mediaTypeArr = UIImagePickerController.availableMediaTypes(for: UIImagePickerController.SourceType.camera) {
//
//                //判断数组中是否存在kUTTypeMovie和kUTTypeImage类型（需要import MobileCoreServices）
//                //kUTTypeMovie 表示可以录制带有音频的视频
//                //kUTTypeImage 表示可以拍摄照片
//
//                if mediaTypeArr.contains(String(kUTTypeMovie)) && mediaTypeArr.contains(String(kUTTypeImage)){
//
//                    //创建一个UIImagePickerController
//                    let pickerControl = UIImagePickerController()
//                    //必须，第一步，设置SourceType，Camera表示相机
//                    pickerControl.sourceType = UIImagePickerController.SourceType.camera
//                    //必须，第二步，设置相机的View中可以使用的媒体类型，这里直接使用上面的mediaTypeArr,它包含了视频和图像
//                    pickerControl.mediaTypes = mediaTypeArr
//                    //必须，第三步，设置delegate：UIImagePickerControllerDelegate,UINavigationControllerDelegate
//                    //这两个必须都写上，可以进入头文件查看到
//                    pickerControl.delegate = self
//
//                    //可选，视频最长的录制时间，这里是10秒，默认为10分钟（600秒）
//                    pickerControl.videoMaximumDuration = 60
//                    //可选，设置视频的质量，默认就是TypeMedium
//                    pickerControl.videoQuality = UIImagePickerController.QualityType.typeMedium
//                    //设置视频或者图片拍摄好后，是否能编辑，默认为false不能编辑
////                    pickerControl.allowsEditing = true
//
//                    //必须，第四步，显示
//                    self.parentViewController?.present(pickerControl, animated: true, completion: nil)
//                }
//            }
//
//        }else{
//
//           let alert = UIAlertController(title: "提示", message: "当前设备不支持摄像头", preferredStyle: .alert)
//            alert.show()
//        }
//    }
    
    
    @objc func audio_record_hanlde(sender:UIButton){
        
        
        if self.vc?.judgementSendMsgOperation() == false{
            return
        }
        
        if self.heightStatus != .speaker {
        
            self.heightStatus = .speaker
            
            inputTextView.resignFirstResponder()
        
           
            
            self.modify_height_status?()
            
        }else{
           
            self.heightStatus = .normal
            
            inputTextView.becomeFirstResponder()
            
            self.modify_height_status?()
        }
        
    }
    
    
    @objc func show_emoji_view(){
        
        
        if self.vc?.judgementSendMsgOperation() == false{
            return
        }
        
        print("【showEmoji---】 上一次的模式",self.heightStatus)
        
        
        
        if self.input_status_control_btn.isSelected {
            self.input_status_control_btn.isSelected = false
            self.heightStatus = .keybroad
            inputTextView.inputView = nil
            inputTextView.returnKeyType = .send
            inputTextView.reloadInputViews()
        }else{
            self.heightStatus = .face
            self.input_status_control_btn.isSelected = true
            self.inputTextView.inputView = self.emojiView
            inputTextView.reloadInputViews()
        }
        
        self.inputTextView.becomeFirstResponder()
        
        
       self.modify_height_status?()
        
    }
    @objc func show_operation_view(){
        
        if self.vc?.judgementSendMsgOperation() == false{
            return
        }
        
        if self.heightStatus == .selectPicture {
            return
        }
        
        self.inputTextView.resignFirstResponder()
    
        self.heightStatus = .selectPicture
        
        self.modify_height_status?()
    }
    
    
}
//MARK: - UIImagePickerControllerDelegate
extension ST_DTInputBar:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)

        
//        if DTLocalStrorage.getData(key: DTLocalStrorage.alreadySelectedImageKey).boolValue{
//
//            return
//        }
        
        picker.dismiss(animated: true, completion: nil)
        
        
//        DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(true))
        
        //info是一个字典，包含了拍摄结果的各种信息
        let infodic:NSDictionary = info as NSDictionary
        
        //获取键值UIImagePickerControllerMediaType的值，表示了当前处理的是视频还是图片
        let mediaType = infodic["UIImagePickerControllerMediaType"] as! String
        
        //如果是视频的话
        if mediaType == kUTTypeMovie as String{
//            saveMovie(infodic: infodic)
        }
            //如果是图片
        else if mediaType == kUTTypeImage as String{
            if let originalImage = self.originalImage(info){
                
                print("BUG拍图-originalImage.size:",originalImage.size)
                
//                let thumbnailImage = originalImage.resize_image(targetWidth: 140)
                
                //                originalImage.scaled(toWidth: 140)
                self.heightStatus = .normal
                self.modify_height_status?()
                
            }else{
//                DTLocalStrorage.setData(key: DTLocalStrorage.alreadySelectedImageKey, value: JSON(false))
            }
        }
    }
//    func fix_orientation(img:UIImage) -> UIImage {
//         let rect = CGRect(x: 0, y: 0, width: img.size.height, height: img.size.width)
//        UIGraphicsBeginImageContextWithOptions(rect.size, false, img.scale)
//       
//        img.draw(in: rect)
//        
//        let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
//        UIGraphicsEndImageContext()
//        
//        return normalizedImage
//    }
    //保存视频方法
    func saveMovie(mediaStr:String){
        //系统保存到tmp目录里的视频文件的路径
        
             let mediaUrl = URL.init(fileURLWithPath: mediaStr)
            if let image = mediaUrl.thumbnail(){
                
                var thumbnailImage:UIImage!
                
//                【重点】录制的库 有问题 需要 旋转 90度
                if image.size.height > 280*2{
                    thumbnailImage = image.resize_image(targetHeight: 280*2)
                }else{
                    thumbnailImage = image
                }
                
                thumbnailImage = thumbnailImage.rotated(by: .pi/2.0)

                    main_thread_execute {
                        
                        self.heightStatus = .normal
                        self.modify_height_status?()
                        
                        
                        if let thumbnailUrl =  self.save_image_to_document(image: thumbnailImage){
                            
                            self.send_video_closure?(thumbnailUrl.path,thumbnailImage.size,mediaStr)
                            
                        }
                    }
            }

    }
  
    
    func originalImage(_ info: [String : Any]) -> UIImage? {
//        return info[UIImagePickerControllerOriginalImage] as? UIImage
        if let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage{
            
            return image.fix_orientation()
            
        }
        
        return nil
    }
    
}

extension ST_DTInputBar:EmojiViewDelegate{
    
    func emojiViewDidPressSendButton(_ emojiView: EmojiView) {
        
        guard self.inputTextView.text.count > 0 else {
            return
        }
        self.send_text_closure?(inputTextView.text)
        inputTextView.text = ""
    }
    
    func emojiViewDidSelectEmoji(_ emoji: String, emojiView: EmojiView) {
        
        inputTextView.insertText(emoji)
    }
    
    func emojiViewDidPressChangeKeyboardButton(_ emojiView: EmojiView) {
        inputTextView.inputView = nil
        inputTextView.returnKeyType = .send
        inputTextView.reloadInputViews()
    }
    
    func emojiViewDidPressDeleteBackwardButton(_ emojiView: EmojiView) {
        inputTextView.deleteBackward()
    }
    
    func emojiViewDidPressDismissKeyboardButton(_ emojiView: EmojiView) {
        inputTextView.resignFirstResponder()
    }
    
}


extension ST_DTInputBar:UITextViewDelegate{
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        
        if textView.textColor == input_placeholder_text_color {
            textView.text = nil
            textView.textColor = input_text_color
        }
    }
    
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        
        if self.vc?.judgementSendMsgOperation() == false{
            return false
        }
        
        return true
    }
    
    
    func textViewDidEndEditing(_ textView: UITextView) {
        
        if textView.text.isEmpty {
            textView.text = input_placeholder_text
            textView.textColor = input_placeholder_text_color
        }
    }
    
    
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if text == "\n" {
            self.send_text_closure?(textView.text)
            textView.text = ""
            return false
        }
        return true
    }
    
}

//
//extension URL{
//
//    func thumbnailForVideo() -> UIImage? {
//
//        let asset = AVAsset(url: self)
//
//        let assetImageGenerator = AVAssetImageGenerator(asset: asset)
//
//        var time = asset.duration
//        time.value = min(time.value, 2)
//
//        do {
//            let imageRef = try assetImageGenerator.copyCGImage(at: time, actualTime: nil)
//            return UIImage(cgImage: imageRef)
//        } catch {
////            print("error")
//            return nil
//        }
//    }
//}

// Helper function inserted by Swift 4.2 migrator.
func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
	return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}

// Helper function inserted by Swift 4.2 migrator.
func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
	return input.rawValue
}



//MARK: - Emoji Model

enum ChatEmojiDisplayStatus:Int {
    case enable,hidden
}

class ChatEmojiCellModel {
    
    var emojiID = UUID().uuidString
    
    var displayStatus = ChatEmojiDisplayStatus.hidden
    
    var emojiUrl = ""
    
    var oldVerIndex:String?
    
}


